package com.zcgame.loadimagedemo.utils

import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.os.Build
import android.os.Environment
import android.os.FileUtils
import android.provider.MediaStore
import android.widget.Toast
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import kotlin.IllegalArgumentException

/**
 *@author:huangLJ
 *@date:2021/7/19 18:03
 */
object IOUtils {
    /**
     * 复制文件
     * [source] 被复制的文件
     * [dest] 要复制的文件
     */
    fun copyFileUsingChannels(source:File,dest:File){
        val inChannel = FileInputStream(source).channel
        val outChannel = FileOutputStream(dest).channel
        outChannel.transferFrom(inChannel,0,inChannel.size())
        inChannel.close()
        outChannel.close()
    }

    /**
     * 添加照片至图库
     * 很管用的一个方法，就是高版本被弃用了
     */
    fun scannerImage1(context:Context,resources: File){
        val result = MediaStore.Images.Media.insertImage(
            context.contentResolver, resources.path, resources.absolutePath, "image/jpeg"
        )
        if(result.isNotEmpty()){
            Toast.makeText(context,"照片已保存至图库",Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 添加照片至图库
     *高版本好像不适用了，而且在低版本中用起来也有问题
     */
    fun scannerImage2(context: Context,resources: File){
        MediaScannerConnection.scanFile(context, arrayOf(resources.path),null,null)

    }

    /**
     * 既兼容高版本又兼容低版本
     */
    fun saveImage2Gallery(context: Context,bitmap:Bitmap,file:File){
        val outputStream = BufferedOutputStream(FileOutputStream(file))
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream)

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            val currentTimeMillis = System.currentTimeMillis()
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_PICTURES)
            values.put(MediaStore.MediaColumns.DISPLAY_NAME,file.path)
            values.put(MediaStore.MediaColumns.MIME_TYPE,"image/*")
            values.put(MediaStore.MediaColumns.DATE_ADDED,currentTimeMillis/1000)
            values.put(MediaStore.MediaColumns.DATE_MODIFIED,currentTimeMillis/1000)
            val resolver = context.contentResolver
            val url = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                ?: throw IllegalArgumentException("photo url is null")
            val outputStream = resolver.openOutputStream(url)
            val inputStream = FileInputStream(file)
            //自带的复制工具
            FileUtils.copy(inputStream,outputStream!!)
            inputStream.close()
            outputStream.close()
        }else{
            MediaScannerConnection.scanFile(
                context, arrayOf(file.absolutePath), arrayOf("image/*"),null
            )
        }

    }
}